import { useEffect, useState, useCallback, useRef } from 'react'
import MarkdownPreview from '@uiw/react-markdown-preview'
import { useParams } from 'react-router-dom'
import MarkdownSidebar from '@/components/markdown-side/MarkdownSidebar.tsx'
import { _getAssets } from '@/utils/assets.ts'
import { getRandomPoetry, Poetry } from '@/utils/poems.ts'
import styles from './ArticleDetail.module.scss'
import { ArticleListVO } from '@/http/article/article.types.ts'
import { _detailArticle } from '@/http/article/article.service.ts'
import { Response } from '@/http/public.types.ts'

function Article() {
  const [currentPoems, setCurrentPoems] = useState<Poetry | null>(null)
  const [displayText, setDisplayText] = useState('') // 存储逐字显示的文本
  const [isTyping, setIsTyping] = useState(false) // 控制是否正在输入
  const interval = useRef<NodeJS.Timeout | null>(null) // 用来存储 setInterval 的引用
  const indexRef = useRef(0) // 用 useRef 来存储 index，避免每次渲染时被重置
  const source = useRef<ArticleListVO>()
  const { id } = useParams()

  useEffect(() => {
    setCommonBg()
    const poems = getRandomPoetry()
    setCurrentPoems(poems)

    return () => {
      if (interval.current) {
        clearInterval(interval.current)
      }
    }
  }, [])

  useEffect(() => {
    function init() {
      // 从react-router-dom获取传递的id， navigate(`/article-detail/${id}`)
      _detailArticle(id as string).then((res) => {
        if (res.code === Response.SUCCESS) {
          source.current = res.data
        }
      })
    }
    init()
  }, [id])

  const setCommonBg = () => {
    const bgList = ['article-bg.jpg']
    const randomIndex = Math.floor(Math.random() * bgList.length)
    document.documentElement.style.setProperty(
      '--common-bg',
      `url(${_getAssets(bgList[randomIndex], 'bg')}` + ')'
    )
  }

  // function getFirstChar(str: string): string {
  //   return str.charAt(0)
  // }

  // 使用 useCallback 来保证 typeText 函数不会在每次渲染时重新定义
  const typeText = useCallback((text: string) => {
    const poems = getRandomPoetry()
    setCurrentPoems(poems)
    indexRef.current = 0 // 重置 index

    // setDisplayText(getFirstChar(text)) // 清空之前的内容
    setDisplayText('') // 清空之前的内容
    setIsTyping(true)

    if (interval.current) {
      clearInterval(interval.current) // 如果之前有定时器，先清除
    }

    interval.current = setInterval(() => {
      setDisplayText((prevText) => {
        if (text[indexRef.current] !== undefined) {
          return prevText + text[indexRef.current]
        }
        return prevText
      })
      indexRef.current++ // 使用 useRef 的 index

      if (indexRef.current === text.length) {
        clearInterval(interval.current as any) // 输入完成，清除定时器
        setIsTyping(false) // 设置为不在输入
        setTimeout(() => {
          setDisplayText('') // 清空文本，准备重新开始
          typeText(text) // 重新开始逐字输入
        }, 5 * 1000) // 停留5秒后重新开始
      }
    }, 200) // 每200ms显示一个字符
  }, []) // useCallback 的依赖项为空数组，表示 typeText 不会改变

  useEffect(() => {
    if (currentPoems?.content) {
      typeText(currentPoems.content)
    }
  }, [currentPoems, typeText]) // 添加 typeText 到依赖项数组

  return (
    <div className={styles.article}>
      <div className={styles.articleMain}>
        <div className={styles.header}>
          <span className={styles.title}>{currentPoems?.title}~</span>
          <div className={styles.poemsContainer}>
            {displayText}
            {isTyping && <span className={styles.cursor}></span>} {/* 仅在正在输入时显示光标 */}
          </div>

          <div className={styles.wave1}></div>
          <div className={styles.wave2}></div>
        </div>
        <div className={styles.body}>
          <div className={styles.left}>
            <h1>{source.current?.articleName}</h1>
            <MarkdownPreview source={source.current?.content} style={{ width: '100%' }} />
          </div>
          <div className={styles.right}>
            <MarkdownSidebar content={source.current?.content || ''} />
          </div>
        </div>
      </div>
    </div>
  )
}

export default Article
